package __回溯算法

import "sort"

/*
https://leetcode.cn/problems/permutations-ii/

47. 全排列 II
给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。

示例 1：
输入：nums = [1,1,2]
输出：
[

	[1,1,2],
	[1,2,1],
	[2,1,1]]

示例 2：
输入：nums = [1,2,3]
输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
*/
var (
	res47  [][]int
	path47 []int
	used47 []bool // state的缩写
)

func permuteUnique(nums []int) [][]int {
	res47, path47 = make([][]int, 0), make([]int, 0, len(nums))
	used47 = make([]bool, len(nums))
	sort.Ints(nums)
	dfs47(nums, 0)
	return res47
}
func dfs47(nums []int, cur int) {
	if cur == len(nums) {
		tmp := make([]int, len(path47))
		copy(tmp, path47)
		res47 = append(res47, tmp)
	}
	for i := 0; i < len(nums); i++ {
		if i != 0 && nums[i] == nums[i-1] && !used47[i-1] { // 去重，用st来判别是深度还是广度
			continue
		}
		if !used47[i] {
			path47 = append(path47, nums[i])
			used47[i] = true
			dfs47(nums, cur+1)
			used47[i] = false
			path47 = path47[:len(path47)-1]
		}
	}
}
